import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Table,
  Form,
  Select,
  Input,
  Card,
  Button,
  Cascader,
  Row,
  Col,
  Modal,
  Collapse,
  Radio,
  Tooltip,
  message,
} from 'antd';

import ImageUploader from '../Attachment/ImageUploader';
import AttachmenTable from '../Attachment/AttachmentTable';
import nopictures from '../../../assets/nopictures3.svg';
import ImageDisplayer from '../Attachment/ImageDisplayer';
import { solo } from '../../../common/solo';

const FormItem = Form.Item;

const formItemLayout = {
  labelcol: {
    span: 24,
  },
  wrappercol: {
    span: 24,
  },
};

@connect(({ risk, apply }) => ({
  risk,
  apply,
}))
@Form.create()
export default class AssetEditor extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      assetEditorFlag: false,
      id: '',
      channelId: '',
      assetDetails: null,
      applyBranchCarTypeList: [],
      applySystemCarList: null,
      applyModelCarList: null,
      applyCarValue: null,
      applyBranchCarPrice: null,
      applyFundAccount: null,
      carType: null,
      imageMap: {
        invoiceImg: [],
        insuranceImg: [],
      },
      carTypeModalVisible: false,
      carTypeFlag: false,
      carTypeName: null,
      applyCarTypeName: null,
    };
  }

  componentDidMount() {
    const { dispatch, location } = this.props;
    // const params = querystring.parse(location.search.slice(1));
    const { apply: { applyListDetails } } = this.props;
    const { assets } = applyListDetails;
    const { asset } = assets;
    // console.log("asset", asset)
    // dispatch({//获取车品牌
    //   type: 'apply/getCarBrandList',
    //   callback: () => {
    //     const { apply: { applyBranchCarList } } = this.props;
    //     // console.log("applyBranchCarList", applyBranchCarList)
    //     applyBranchCarList &&
    //       this.setState({
    //         applyBranchCarTypeList: applyBranchCarList,
    //       })
    //   }
    // });

    let imageMap = this.state.imageMap;
    if (assets && assets.invoice.attachs.length > 0) {
      for (let i = 0; i < assets.invoice.attachs.length; i++) {
        imageMap.invoiceImg.push({
          uid: assets.invoice.attachs[i],
          name: assets.invoice.attachs[i],
          key: assets.invoice.attachs[i],
          status: 'done',
          url: solo.imgShow + assets.invoice.attachs[i],
        });
      }
    }
    if (assets && assets.insurance.attachs.length > 0) {
      for (let i = 0; i < assets.insurance.attachs.length; i++) {
        imageMap.insuranceImg.push({
          key: assets.insurance.attachs[i],
          uid: assets.insurance.attachs[i],
          name: assets.insurance.attachs[i],
          status: 'done',
          url: solo.imgShow + assets.insurance.attachs[i],
        });
      }
    }

    this.setState({
      id: this.props.id,
      imageMap,
      assetDetails: asset,
      applyBranchCarPrice: asset.msrp,
      applyCarValue: asset.carTypeId,
      carTypeName: asset.carType,
      // assetGpsData: assets.pickCar,
    });
    dispatch({
      type: 'apply/getProList',
      payload: {
        offset: 0,
        limit: 10,
      },
    });
  }

  columns = [
    {
      title: '名称',
      dataIndex: 'dealerName',
      key: 'dealerName',
    },
    {
      title: '简称',
      dataIndex: 'simpleName',
      key: 'simpleName',
    },
    {
      title: '账号',
      dataIndex: 'fundAccount',
      key: 'fundAccount',
    },
  ];

  handleSaveAssetsr = () => {
    const { dispatch } = this.props;

    const { validateFieldsAndScroll } = this.props.form;
    validateFieldsAndScroll((error, values) => {
      if (!error) {
        dispatch({
          type: 'apply/saveAssets',
          payload: {
            id: this.props.projectId,
            channelId: this.state.assetDetails.id,
            carType: this.state.carType,
            ...values,
          },
          callback: () => {
            const { apply: { applyResult } } = this.props;
            if (applyResult.code == '200') {
              message.success('提交成功');
              dispatch({
                type: 'apply/detailsApply',
                payload: {
                  projectId: this.props.projectId,
                },
              });
            } else {
              message.error(applyResult.message);
            }
          },
        });
      }
    });
  };

  handleSelectCustomerClick = () => {
    this.setState({
      assetEditorFlag: true,
    });
  };

  handleCancelAsset = () => {
    this.setState({
      assetEditorFlag: false,
    });
  };

  handleOKAssetsr = () => {
    this.setState({
      assetEditorFlag: false,
    });
  };

  handleStandardTableChange = e => {
    this.props.dispatch({
      type: 'apply/getProList',
      payload: { offset: (e.current - 1) * e.pageSize, limit: e.pageSize },
    });
  };

  handleAssetSelect = record => {
    // console.log("recohandleCustomerSelectrd", record)
    this.setState({
      assetDetails: record,
    });
  };

  //获取车系
  handleCarBranch = value => {
    this.props.dispatch({
      type: 'apply/getCarSystemList',
      payload: {
        brandId: value,
      },
      callback: () => {
        const { apply: { applySystemCarList } } = this.props;
        applySystemCarList &&
          this.setState({
            applySystemCarList,
          });
      },
    });
  };

  //车型
  handleCarModel = value => {
    this.props.dispatch({
      type: 'apply/getCarModelList',
      payload: {
        carsystemId: value,
      },
      callback: () => {
        const { apply: { applyModelCarList } } = this.props;
        applyModelCarList &&
          this.setState({
            applyModelCarList,
          });
      },
    });
  };

  handleCarPrice = value => {
    this.state.applyModelCarList.map(item => {
      if (value == item.id) {
        this.setState({
          applyBranchCarPrice: item.modelPrice,
          carType: item.modelName,
        });
      }
    });
  };

  handleCarTypeChange = (value, selectedOptions) => {
    //  console.log("applyCarValue2322221121",value);
    //  console.log("selectedOptions",selectedOptions);

    // console.log("applyCarValue2322221121", selectedOptions),

    this.setState({
      applyCarValue: value,
    });
    if (selectedOptions.length == 3) {
      this.setState({ applyCarTypeName: selectedOptions[2].label, carTypeFlag: true });
    }
    if (value.length == 1) {
      this.handleCarBranch(value[0]);
    }
    if (value.length == 2) {
      this.handleCarModel(value[1]);
    }
    if (value.length == 3) {
      this.handleCarPrice(value[2]);
    }
  };

  loadData = selectedOptions => {
    // console.log("selectedOptions", selectedOptions)
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;
    setTimeout(() => {
      targetOption.loading = false;
      if (this.state.applyCarValue.length == 1) {
        targetOption.children = this.state.applySystemCarList;
      }
      if (this.state.applyCarValue.length == 2) {
        targetOption.children = this.state.applyModelCarList;
      }
      this.setState({
        applyBranchCarTypeList: [...this.state.applyBranchCarTypeList],
      });
    }, 500);
  };

  calcAttachmentData = () => {
    const attachmentData = [
      {
        key: '1',
        name: '提车照片',
        projectInfo: this.props.projectInfo,
        customerId: '',
        fieldName: 'pickCar',
        attachKind: '1620',
        maxCount: 10,
        files: [],
      },
      {
        key: '2',
        name: '行驶证',
        projectInfo: this.props.projectInfo,
        customerId: '',
        fieldName: 'driveLicenseImg',
        attachKind: '1680',
        maxCount: 2,
        files: [],
      },
      {
        key: '3',
        name: '合格证',
        projectInfo: this.props.projectInfo,
        customerId: '',
        fieldName: 'carQualified',
        attachKind: '1670',
        maxCount: 1,
        files: [],
      },
      {
        key: '4',
        name: '登记证',
        projectInfo: this.props.projectInfo,
        customerId: '',
        fieldName: 'carRegister',
        attachKind: '1660',
        maxCount: 1,
        files: [],
      },
      {
        key: '5',
        name: '首付款凭证',
        projectInfo: this.props.projectInfo,
        customerId: '',
        fieldName: 'firstPayImg',
        attachKind: '1610',
        maxCount: 1,
        files: [],
      },
      {
        key: '6',
        name: '其他',
        projectInfo: this.props.projectInfo,
        customerId: '',
        fieldName: 'otherImg',
        attachKind: '1690',
        maxCount: 10,
        files: [],
      },
    ];

    const { apply: { applyListDetails } } = this.props;
    const { assets } = applyListDetails;

    // console.log('calcAttachmentData',assets);
    const { attachs } = assets;

    return attachmentData.map((attachmentMetaInfo, index) => {
      const { fieldName } = attachmentMetaInfo;
      const imageKeyList = attachs[fieldName];
      if (!imageKeyList) {
        return attachmentMetaInfo;
      }
      const imageInfoList = imageKeyList.map(key => {
        return {
          key,
          url: `${solo.imgShow}${key}`,
          status: 'done',
          uid: key,
          name: key,
        };
      });
      attachmentMetaInfo.files = imageInfoList;
      return attachmentMetaInfo;
    });
  };

  hanleAttachmentChanged = (metaInfo, fileList, file) => {
    // console.log('hanleAttachmentChanged metaInfo',metaInfo);
    // console.log('hanleAttachmentChanged fileList',fileList);
    // console.log('hanleAttachmentChanged file',file);
  };

  handleAttachmentRemove = (fieldName, fileInfo) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'apply/deleteFile',
      payload: {
        fileId: fileInfo.key,
      },
    });
  };

  handleImageUploaded = (fieldName, fileList) => {
    switch (fieldName) {
      case '发票':
        this.setState({
          imageMap: { ...this.state.imageMap, invoiceImg: fileList },
        });
        break;
      case '保单':
        this.setState({
          imageMap: { ...this.state.imageMap, insuranceImg: fileList },
        });
        break;
    }
  };

  handleRemoveImage = (fieldName, fileInfo) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'apply/deleteFile',
      payload: {
        fileId: fileInfo.key,
      },
    });
  };

  handleCancelCarType = () => {
    this.setState({ carTypeModalVisible: false });
  };

  handleOKCarType = () => {
    if (!this.state.carTypeFlag) {
      message.warning('请选择车型');
    } else {
      this.setState({
        carTypeModalVisible: false,
        carTypeName: this.state.applyCarTypeName,
      });
    }
  };

  handleCarTypeModalVisible = () => {
    const { dispatch } = this.props;
    dispatch({
      //获取车品牌
      type: 'apply/getCarBrandList',
      callback: () => {
        const { apply: { applyBranchCarList } } = this.props;
        applyBranchCarList &&
          this.setState({
            applyBranchCarTypeList: applyBranchCarList,
          });
      },
    });
    this.setState({ carTypeModalVisible: true });
  };

  render() {
    const { risk, isForFamilyMember } = this.props;
    const { customers } = risk;
    const {
      apply: { applyListDetails, applyLoading, applyProList, applyPage, applyBranchCarList },
    } = this.props;
    const { assets } = applyListDetails;
    const { getFieldDecorator } = this.props.form;
    const { applyDisabled } = this.props;
    const { applyBranchCarTypeList, applySystemCarList, applyModelCarList } = this.state;

    const rowSelection = {
      type: 'radio',
      onSelect: this.handleAssetSelect,
    };

    // console.log("applyBranchCarTypeList", applyBranchCarTypeList && applyBranchCarTypeList)

    return (
      <Form>
        {/* {JSON.stringify(applyBranchCarTypeList)} */}
        <Card type="inner" title="资产信息">
          <Row gutter={16}>
            <Col span={7}>
              <FormItem label="车型" {...formItemLayout}>
                {/* {getFieldDecorator('carTypeId', {
                  // initialValue: assets.asset.carTypeId,
                  initialValue:['1023856867267854337', '999482224251768833', '999511314778337282'],
                })( */}
                {this.state.carTypeName}
                {/* <Cascader
                  defaultValue={['1023856867267854337', '999482224251768833', '999511314778337282']}
                  disabled={applyDisabled}
                  options={applyBranchCarTypeList}
                  loadData={this.loadData}
                  placeholder="请选择"
                  onChange={this.handleCarTypeChange}
                  changeOnSelect
                /> */}
                {/* )} */}
              </FormItem>
            </Col>
            <Col span={1} {...formItemLayout}>
              {applyDisabled ? null : (
                <Tooltip title="选择车辆">
                  <Button
                    onClick={this.handleCarTypeModalVisible}
                    style={{ marginTop: '45px' }}
                    type="dashed"
                    size="small"
                    shape="circle"
                    icon="edit"
                  />
                </Tooltip>
              )}
            </Col>

            <Col span={8}>
              <FormItem label="厂商指导价" {...formItemLayout}>
                {getFieldDecorator('msrp', {
                  initialValue: applyDisabled ? assets.asset.msrp : this.state.applyBranchCarPrice,
                })(<Input readOnly={true} disabled />)}
              </FormItem>
            </Col>
            <Col span={7}>
              <FormItem label="经销商" {...formItemLayout}>
                {getFieldDecorator('dealerName', {
                  initialValue: applyDisabled
                    ? assets.asset.dealerName
                    : this.state.assetDetails && this.state.assetDetails.dealerName,
                })(<Input readOnly={true} disabled />)}
              </FormItem>
            </Col>
            <Col span={1} {...formItemLayout}>
              <Tooltip title="选择经销商">
                <Button
                  onClick={this.handleSelectCustomerClick}
                  style={{ marginTop: '45px' }}
                  type="dashed"
                  size="small"
                  shape="circle"
                  icon="search"
                />
              </Tooltip>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={8}>
              <FormItem label="经销商账号" {...formItemLayout}>
                {getFieldDecorator('bankAccount', {
                  initialValue: applyDisabled
                    ? assets.asset.bankAccount
                    : this.state.assetDetails && this.state.assetDetails.bankAccount,
                })(<Input readOnly={true} disabled />)}
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem label="经销商报价" {...formItemLayout}>
                {getFieldDecorator('dealerPrice', {
                  initialValue: assets.asset.dealerPrice,
                })(<Input placeholder="请输入" disabled={applyDisabled} />)}
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem label="车架号" {...formItemLayout}>
                {getFieldDecorator('carFrame', {
                  initialValue: assets.asset.carFrame,
                })(<Input placeholder="请输入" disabled={applyDisabled} />)}
              </FormItem>
            </Col>
          </Row>
        </Card>
        <Card type="inner" title="提车情况" style={{ marginTop: '16px' }}>
          <Row gutter={16}>
            <Col span={8}>
              <FormItem label="车牌号" {...formItemLayout}>
                {getFieldDecorator('licensePlate', {
                  initialValue: assets.pickCar.licensePlate,
                })(<Input placeholder="请输入" disabled={applyDisabled} />)}
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem label="行驶证号码" {...formItemLayout}>
                {getFieldDecorator('licenseDrive', {
                  initialValue: assets.pickCar.licenseDrive,
                })(<Input placeholder="请输入" disabled={applyDisabled} />)}
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem label="车辆合格证编号" {...formItemLayout}>
                {getFieldDecorator('licenseCar', {
                  initialValue: assets.pickCar.licenseCar,
                })(<Input placeholder="请输入" disabled={applyDisabled} />)}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={8}>
              <FormItem label="车辆登记证编号" {...formItemLayout}>
                {getFieldDecorator('licenseRegister', {
                  initialValue: assets.pickCar.licenseRegister,
                })(<Input placeholder="请输入" disabled={applyDisabled} />)}
              </FormItem>
            </Col>
          </Row>
        </Card>
        <Card type="inner" title="发票信息" style={{ marginTop: '16px' }}>
          <Form>
            <Row gutter={16}>
              <Col span={8}>
                {applyDisabled ? (
                  <FormItem label="发票" {...formItemLayout}>
                    {assets.invoice.attachs.length == 0 ? (
                      <img src={nopictures} style={{ width: '20%', height: '20%' }} />
                    ) : (
                      assets &&
                      assets.invoice.attachs.map(item => {
                        return (
                          <Col span={6}>
                            <ImageDisplayer src={solo.imgShow + item} />
                          </Col>
                        );
                      })
                    )}
                  </FormItem>
                ) : (
                  <FormItem label="发票" {...formItemLayout}>
                    <ImageUploader
                      maxCount={10}
                      fieldName="发票"
                      // label="发票"
                      key={1}
                      maxCount={1}
                      size="small"
                      showRemoveIconType={true}
                      onRemoveImage={this.handleRemoveImage}
                      attachmentData={{
                        projectId: this.props.projectId, //业务ID
                        customerId: '', //客户ID
                        attachType: '0', //0：图片；1：视频
                        attachKind: '1630', //附件种类
                        type: '发票', //图片类型
                      }}
                      fileList={this.state.imageMap.invoiceImg}
                      onImageUploaded={this.handleImageUploaded}
                    />
                  </FormItem>
                )}
              </Col>
              <Col span={8}>
                <FormItem label="发票编号" {...formItemLayout}>
                  {getFieldDecorator('invoiceNumber', {
                    initialValue: assets.invoice.invoiceNumber,
                  })(<Input placeholder="请输入" disabled={applyDisabled} />)}
                  {/* <Button>识别发票信息</Button> */}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem label="开票金额" {...formItemLayout}>
                  {getFieldDecorator('invoicePrice', {
                    initialValue: assets.invoice.invoicePrice,
                  })(<Input placeholder="请输入" disabled={applyDisabled} />)}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem label="开票单位" {...formItemLayout}>
                  {getFieldDecorator('invoiceCompany', {
                    initialValue: assets.invoice.invoiceCompany,
                  })(<Input placeholder="请输入" disabled={applyDisabled} />)}
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Card>
        <Card type="inner" title="保险信息" style={{ marginTop: '16px' }}>
          <Form>
            <Row gutter={16}>
              <Col span={8}>
                {applyDisabled ? (
                  <FormItem label="保单" {...formItemLayout}>
                    {assets.insurance.attachs.length == 0 ? (
                      <img src={nopictures} style={{ width: '20%', height: '20%' }} />
                    ) : (
                      assets &&
                      assets.insurance.attachs.map(item => {
                        return (
                          <Col span={6}>
                            <ImageDisplayer src={solo.imgShow + item} />
                          </Col>
                        );
                      })
                    )}
                  </FormItem>
                ) : (
                  <FormItem label="保单" {...formItemLayout}>
                    <ImageUploader
                      maxCount={10}
                      fieldName="保单"
                      // label="保单"
                      key={1}
                      size="small"
                      maxCount={5}
                      showRemoveIconType={true}
                      onRemoveImage={this.handleRemoveImage}
                      attachmentData={{
                        projectId: this.props.projectId, //业务ID
                        customerId: '', //客户ID
                        attachType: '0', //0：图片；1：视频
                        attachKind: '1640', //附件种类
                        type: '保单', //图片类型
                      }}
                      fileList={this.state.imageMap.insuranceImg}
                      onImageUploaded={this.handleImageUploaded}
                    />
                  </FormItem>
                )}
              </Col>
              <Col span={8}>
                <FormItem label="保单编号" {...formItemLayout}>
                  {getFieldDecorator('insuranceNumber', {
                    initialValue: assets.insurance.invoiceNumber,
                  })(<Input placeholder="请输入" disabled={applyDisabled} />)}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem label="保单金额" {...formItemLayout}>
                  {getFieldDecorator('insurancePrice', {
                    initialValue: assets.insurance.invoicePrice,
                  })(<Input placeholder="请输入" disabled={applyDisabled} />)}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem label="保险公司" {...formItemLayout}>
                  {getFieldDecorator('insuranceCompany', {
                    initialValue: assets.insurance.invoiceCompany,
                  })(<Input placeholder="请输入" disabled={applyDisabled} />)}
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Card>
        <Card title="附件管理" type="inner" style={{ marginTop: '16px' }}>
          <AttachmenTable
            projectInfo={{ projectId: this.props.projectId }}
            data={this.calcAttachmentData()}
            applyDisabled={applyDisabled}
            onAttachmentChanged={this.hanleAttachmentChanged}
            onAttachmentRemove={this.handleAttachmentRemove}
          />
        </Card>
        <FormItem
          style={{ marginLeft: '30px', marginTop: '30px' }}
          wrappercol={{ span: 21, offset: 3 }}
          label=""
        >
          {applyDisabled ? (
            ''
          ) : (
            <Button type="primary" onClick={this.handleSaveAssetsr} loading={applyLoading}>
              保存
            </Button>
          )}
        </FormItem>

        <Modal
          width="900px"
          title="选择经销商"
          visible={this.state.assetEditorFlag}
          onCancel={this.handleCancelAsset}
          onOk={this.handleOKAssetsr}
        >
          <Table
            style={{ marginTop: '10px' }}
            size="middle"
            columns={this.columns}
            pagination={applyPage}
            rowKey="id"
            loading={applyLoading}
            rowSelection={rowSelection}
            dataSource={applyProList.list}
            onChange={this.handleStandardTableChange}
          />
        </Modal>

        <Modal
          width="500px"
          title="车辆选择"
          visible={this.state.carTypeModalVisible}
          onCancel={this.handleCancelCarType}
          onOk={this.handleOKCarType}
        >
          {/* <FormItem label="车型" {...formItemLayout1}> */}
          <Cascader
            style={{ textAlign: 'center', width: '450px' }}
            disabled={applyDisabled}
            options={applyBranchCarTypeList}
            loadData={this.loadData}
            placeholder="请选择"
            onChange={this.handleCarTypeChange}
            changeOnSelect
          />
          {/* </FormItem> */}
        </Modal>
      </Form>
    );
  }
}
